package com.linkai.jacklinmap.Activity.Mine;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linkai.jacklinmap.R;
import com.linkai.jacklinmap.Service.MyService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 创建日期：2021/6/18 16:13
 *
 * @author 林凯
 * 文件名称： SettingActivity.java
 * 类说明： 显示设置信息。
 * 同时用来测试
 * （1）测试网络功能，请求高德天气API   -- OK
 * （2）测试通知功能，
 */
public class SettingActivity extends AppCompatActivity implements View.OnClickListener {


    TextView setting_developer, setting_weather, response_text, setting_notification, setting_music,setting_music_end;
    TextView setting_broadcast;

    // 对话框
    AlertDialog alert;
    AlertDialog.Builder builder;

    Intent intentMusic;

    private MyBroadcastReceiver broadcastReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_my);

        setting_developer = findViewById(R.id.setting_developer);
        setting_weather = findViewById(R.id.setting_weather);
        response_text = findViewById(R.id.response_text);
        setting_notification = findViewById(R.id.setting_notification);
        setting_music = findViewById(R.id.setting_music);
        setting_music_end = findViewById(R.id.setting_music_end);
        setting_broadcast = findViewById(R.id.setting_broadcast);


        setting_developer.setOnClickListener(this::onClick);
        setting_weather.setOnClickListener(this::onClick);
        setting_notification.setOnClickListener(this::onClick);
        setting_music.setOnClickListener(this::onClick);
        setting_music_end.setOnClickListener(this::onClick);
        setting_broadcast.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.setting_developer: {

                startActivity(new Intent(this, DeveloperActivity.class));

                break;
            }
            case R.id.setting_weather: {
//                sendRequestWithHttpURLConnection();
//                showAlert();
                break;
            }
            case R.id.setting_notification: {


                Intent notificationIntent = new Intent(this, SettingActivity.class);
                notificationIntent.setAction(Intent.ACTION_MAIN);
                notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);


                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

                String channelId = "myNotification";
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification.Builder builder;
                Notification notification = null;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                    // 8.0以上需要设置 Channel
                    NotificationChannel mChannel = new NotificationChannel(channelId, "JackLinMap", NotificationManager.IMPORTANCE_HIGH);
                    notificationManager.createNotificationChannel(mChannel);

                    builder = new Notification.Builder(this);
                    builder.setChannelId(channelId);
                    builder.setContentTitle("消息提示");
                    builder.setContentText("JackLinMap正在运行");
                    builder.setSmallIcon(R.mipmap.ic_launcher);
                    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_map));
                    builder.setAutoCancel(true);        //设置点击之后自动消失
                    // 设置 PendingIntent
                    builder.setContentIntent(pendingIntent);

                    notification = builder.build();
                } else {
                    builder = new Notification.Builder(this);
                    builder.setContentTitle("消息提示");
                    builder.setContentText("JackLinMap正在运行");
                    builder.setSmallIcon(R.mipmap.ic_launcher);
                    notification = builder.build();
                }
                notificationManager.notify(2, notification);

                break;
            }
            case R.id.setting_music: {


                intentMusic = new Intent(getApplicationContext(), MyService.class);

                if (Build.VERSION.SDK_INT >= 26) {
                    startForegroundService(intentMusic);
                } else {
                    startService(intentMusic);
                }
                break;
            }
            case R.id.setting_music_end: {

                stopService(intentMusic);
                break;
            }
            case R.id.setting_broadcast: {

                //动态注册广播接收器
                broadcastReceiver = new MyBroadcastReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("com.example.communication.RECEIVER");
                registerReceiver(broadcastReceiver, intentFilter);

                Intent intent = new Intent("com.example.communication.RECEIVER");
                intent.putExtra("option", "pause");
                System.out.println("send broadcast");
                sendBroadcast(intent);


            }

        }
    }

    // 请求高德地图API，获取天气信息(测试使用，在 RunActivity 才会实际使用)
    private void sendRequestWithHttpURLConnection() {

        // 开启新线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader bufferedReader = null;

                try {
                    URL url = new URL("https://restapi.amap.com/v3/weather/weatherInfo?city=360100&key=91d01733ad26a1ebf48d3367916cb4ff");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream inputStream = connection.getInputStream();

                    // 下面对获取到的输入流进行读取
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        response.append(line);
                    }

                    showResponse(response.toString());

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

            }
        }).start();
    }

    // 处理得到的响应结果
    public void showResponse(final String response) {
        System.out.println(response);

        JSONObject jsonObject = JSONObject.parseObject(response);
//        System.out.println(jsonObject);
        JSONArray jsonArray = (JSONArray) jsonObject.get("lives");
        JSONObject weatherObject = (JSONObject) jsonArray.get(0);
        System.out.println(weatherObject.get("province"));
        System.out.println(weatherObject.get("weather"));

        /*
        {"lives":[{"province":"江西","city":"南昌市","adcode":"360100","windpower":"4","weather":"阴","temperature":"32","humidity":"71","reporttime":"2021-06-18 12:34:01","winddirection":"西南"}],
        "count":"1",
        "infocode":"10000",
        "status":"1",
        "info":"OK"}

        * */

        response_text.setText(response);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("receive broadcast");
            Toast.makeText(getApplicationContext(), "broadcast", Toast.LENGTH_SHORT).show();
            System.out.println(intent.getStringExtra("option"));
        }
    }

//    public class MyBroadcastReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            System.out.println("receive broadcast");
//            Toast.makeText(getApplicationContext(), "broadcast", Toast.LENGTH_SHORT).show();
//        }
//    }

}